package com.yichen.ycapiclientSDK.client;



import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.yichen.ycapiclientSDK.model.User;
import com.yichen.ycapiclientSDK.utils.SignUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: yichenwu
 * @Date:2024/7/29 16:17
 */

/**
 * 调用第三方接口的客户端
 */
public class YcApiClient {
    public static final String GLOBAL_URL_PREFIX = "http://localhost:8888/api/name/";

    private String accessKey;
    private String secretKey;

    public YcApiClient(String accessKey, String secretKey) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
    }

    public String getNameByGet(String name) {
        //可以单独传入http参数，这样参数会自动做URL编码，拼接在URL中
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);
        String result = HttpUtil.get(GLOBAL_URL_PREFIX, paramMap);
        System.out.println("GET:" + result);
        return result;
    }

    public String getNameByPost(String name) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);
        String result = HttpUtil.post(GLOBAL_URL_PREFIX, paramMap);
        System.out.println("POST:" + result);
        return result;
    }

    public String getUserNameByPost(User user) {
        String json = JSONUtil.toJsonStr(user);
        String url = GLOBAL_URL_PREFIX + "user";
        HttpResponse httpResponse = HttpRequest.post(url)
                .addHeaders(getHeaderMap(json))
                .body(json)
                .execute();
        System.out.println("状态码：" + httpResponse.getStatus());
        String body = httpResponse.body();
        System.out.println("POST Restful:" + body);
        return body;
    }

    // 创建一个私有方法，用于构造请求头
    private Map<String, String> getHeaderMap(String requestBody) {
        // 创建一个新的 HashMap 对象
        Map<String, String> hashMap = new HashMap();
        // 将 "accessKey" 和其对应的值放入 map 中
        hashMap.put("accessKey", accessKey);
        // 4位随机数
        // todo: 后端存储这个随机数
        hashMap.put("nonce", RandomUtil.randomNumbers(4));
        // 时间戳 - 秒
        hashMap.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
        // 用户请求体
        hashMap.put("requestBody", requestBody);
        // 签名
        // 注意：不能直接发送密钥
        // hashMap.put("secretKey", secretKey);
        hashMap.put("sign", SignUtils.getSign(requestBody, secretKey));

        // 返回构造的请求头 map
        return hashMap;
    }
}
